package com.jieshuibao.controller;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jieshuibao.common.config.Const;
import com.jieshuibao.common.config.Global;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.model.db.OfficialAdvisory;
import com.jieshuibao.model.db.OfficialAdvisoryExample;
import com.jieshuibao.model.db.OfficialAdvisoryExample.Criteria;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.domain.OfficialAdvisoryReq;
import com.jieshuibao.model.domain.OfficialAdvisoryRes;
import com.jieshuibao.service.CheckUserOnlineService;
import com.jieshuibao.service.OfficialAdvisoryService;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.service.UserService;
import com.jieshuibao.util.Base64ForImg;
import com.jieshuibao.util.DeleteHtmlUtil;
import com.jieshuibao.util.StringUtils;
import com.jieshuibao.util.UUIDGenerator;

@Controller
@RequestMapping(value = "/official")
public class OfficialAdvisoryController {
	
	private static final Logger logger = LoggerFactory
			.getLogger("OfficialAdvisoryController.class");
	private static final ObjectMapper mapper = new ObjectMapper();
	@Resource
	private RedisService redisService;
	@Resource
	private UserService userService;
	@Resource
	private CheckUserOnlineService checkUserOnlineService;

	@Value("${question.images.path}")
	private String questionImagesPath;

	@Resource
	private OfficialAdvisoryService officialAdvisoryService;

	/**
	 * 官方咨询添加
	 * 
	 * @param request
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Object officialAdd(HttpServletRequest request,
			@RequestBody OfficialAdvisoryReq req) {
		OfficialAdvisoryRes res = new OfficialAdvisoryRes();

		try {
			String cookieId = request.getHeader("cookieId");
			String online = checkUserOnlineService.isOnline(cookieId);
			if (online.equals(BaseRes.RELOGIN_CODE)) {
				res.setCode(BaseRes.RELOGIN_CODE);
				res.setDes(BaseRes.RELOGIN_DES);
				return res;
			}
			String question = req.getQuestion();
			String[] imgs = req.getImgs();
			if (StringUtils.isEmpty(question)) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes("问题为空");
				return res;
			}
			User user = userService.getUserByPhoneNumber(online);

			if (user != null) {
				Integer advisoryNum = user.getAdvisoryNum();
				if (advisoryNum == null || advisoryNum < 1) {
					res.setCode(BaseRes.ADVISORYNUM_CODE);
					res.setDes("咨询次数已经使用完！");
					return res;
				}
				String vip = user.getVip();
				if(vip.equals(Const.USER_VIP_NO)){
					res.setCode(BaseRes.NOVIP_CODE);
					res.setDes("你不是会员");
					return res;
				}
				Date date = new Date();
				Date invalidTime = user.getAdvisoryInvalidTime();
				if(invalidTime!=null&&invalidTime.before(date)){
					res.setCode(BaseRes.ERRORPARAM_CODE);
					res.setDes("咨询次数已经过期！");
					return res;
				}
				OfficialAdvisory officialAdvisory = new OfficialAdvisory();

				String uuid = UUIDGenerator.getUUID();

				officialAdvisory.setUuid(uuid);
				officialAdvisory.setUserId(online);
				officialAdvisory.setDelFlag(Global.SHOW);
				
				
				officialAdvisory.setQuDate(date);
				officialAdvisory.setQuestion(question);
				officialAdvisory.setUpdateDate(date);

				officialAdvisory.setRed("1");
				officialAdvisory.setStatus(Const.OFFICIAL_ADVISORY_WAIT);
				if (imgs != null) {
					String[] generateBach = Base64ForImg.GenerateBach(imgs,
							questionImagesPath);
					String join = StringUtils.join(generateBach, ",");
					officialAdvisory.setImgs(join);
				}
				User user2 = new User();
				user2.setPhoneNumber(online);
				user2.setAdvisoryNum(-1);
				officialAdvisoryService.addOfficialAdvisoryAndUpdateUser(
						officialAdvisory, user2);
				res.setTime(date);
				res.setUuid(uuid);
				res.setCode(BaseRes.SUCCESS_CODE);
				res.setDes("提交成功");
				return res;
			} else {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes("数据错误");
				return res;
			}

		} catch (Exception e) {
			e.printStackTrace();

			res.setCode(BaseRes.FAIL_CODE);
			res.setDes("网络抖动了");
			return res;

		}

	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public Object officialList(HttpServletRequest request,
			@RequestBody OfficialAdvisoryReq req) {
		OfficialAdvisoryRes res = new OfficialAdvisoryRes();

		try {
			String cookieId = request.getHeader("cookieId");
			String userId = checkUserOnlineService.isOnline(cookieId);
			if (userId.equals(BaseRes.RELOGIN_CODE)) {
				res.setCode(BaseRes.RELOGIN_CODE);
				res.setDes(BaseRes.RELOGIN_DES);
				return res;
			}
			logger.error("接收到的索引："+mapper.writeValueAsString(req));
			int sinceId = req.getSinceId();
			int maxId = req.getMaxId();
			OfficialAdvisoryExample officialAdvisoryExample = new OfficialAdvisoryExample();

			officialAdvisoryExample.setPageIndex(sinceId - 1);
			officialAdvisoryExample.setPageSize(maxId - sinceId + 1);
			officialAdvisoryExample
					.setOrderByClause("official_advisory.updateDate desc");
			Criteria createCriteria = officialAdvisoryExample.createCriteria();

			createCriteria.andDelFlagEqualTo(Global.SHOW);
			createCriteria.andUserIdEqualTo(userId);
			List<OfficialAdvisory> data = officialAdvisoryService
					.getPageOfficialAdvisory(officialAdvisoryExample);
			for (OfficialAdvisory officialAdvisory : data) {
				String answer = officialAdvisory.getAnswer();
				if (!StringUtils.isEmpty(answer)) {
					String textFromHtml = DeleteHtmlUtil
							.getTextFromHtml(answer);
					officialAdvisory.setAnswer(textFromHtml);
				}
			}

			res.setData(data);
			res.setSinceId(sinceId);
			res.setMaxId(maxId - 1 + data.size());
			res.setRows(data.size());
			res.setCode(BaseRes.SUCCESS_CODE);
			res.setDes(BaseRes.SUCCESS_DES);
			return res;

		} catch (Exception e) {
			e.printStackTrace();

			res.setCode(BaseRes.FAIL_CODE);
			res.setDes("网络抖动了");
			return res;

		}

	}
	
	@RequestMapping(value = "/details", method = RequestMethod.POST)
	@ResponseBody
	public  Object rofficialdetails(HttpServletRequest request,
			@RequestBody OfficialAdvisoryReq req) {
			BaseRes<OfficialAdvisory> res = new BaseRes<OfficialAdvisory>();
			
		try {
			String uuid = req.getUuid();
			if(StringUtils.isEmpty(uuid)){
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes("uuid为空");
				return res;
			}
			OfficialAdvisory data = officialAdvisoryService.getOfficialAdvisoryByUuid(uuid);
			if(data==null){
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes("uuid错误");
				return res;
			}
			String red = data.getRed();
			if(red.equals("0")){
				OfficialAdvisory officialAdvisory = new OfficialAdvisory();
				officialAdvisory.setUuid(uuid);
				officialAdvisory.setRed("1");
				officialAdvisoryService.updateOfficialAdvisory(officialAdvisory);
			}
			res.setData(data);
			res.setCode(BaseRes.SUCCESS_CODE);	
			res.setDes(BaseRes.SUCCESS_DES);
			return res;
		
			} catch (Exception e) {
			e.printStackTrace();
			
			res.setCode(BaseRes.FAIL_CODE);
			res.setDes("网络抖动了");
			return res;
			
		}

	}

}
